package com.ssy.lingxi.product.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.manage.ShopTypeEnum;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.product.api.enums.FreightStatusEnum;
import com.ssy.lingxi.product.api.model.request.warehouse.*;
import com.ssy.lingxi.product.api.model.response.warehouse.*;
import com.ssy.lingxi.product.common.InvoicesTypeConstant;
import com.ssy.lingxi.product.entity.commodity.CommodityUnitPriceAndPic;
import com.ssy.lingxi.product.entity.warehouse.*;
import com.ssy.lingxi.product.repository.channelCommodity.ChannelCommodityShopRepository;
import com.ssy.lingxi.product.repository.commodity.CommodityShopRepository;
import com.ssy.lingxi.product.repository.commodity.CommodityUnitPriceAndPicRepository;
import com.ssy.lingxi.product.repository.warehouse.*;
import com.ssy.lingxi.product.service.FreightSpaceService;
import com.ssy.lingxi.product.service.ICommodityService;
import com.ssy.lingxi.product.utils.RedisLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FreightSpaceServiceImpl implements FreightSpaceService {
    @Resource
    FreightSpaceRepository freightSpaceRepository;

    @Resource
    ShopFreightSpaceRepository shopFreightSpaceRepository;

    @Resource
    IRedisStringUtils redisStringUtils;

    @Resource
    FreightSpaceAllotLogRepository freightSpaceAllotLogRepository;

    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    FreightSpaceMemberRepository freightSpaceMemberRepository;

    @Resource
    PositionInventoryDeductionRecordRepository positionInventoryDeductionRecordRepository;

    @Resource
    InventoryRepository inventoryRepository;

    @Resource
    WarehouseRepository warehouseRepository;

    @Resource
    CommodityShopRepository commodityShopRepository;

    @Resource
    ChannelCommodityShopRepository channelCommodityShopRepository;

    @Resource
    ICommodityService commodityService;

    @Resource
    CommodityUnitPriceAndPicRepository commodityUnitPriceAndPicRepository;

    /**
     * 仓位库存列表查询
     *
     * @param request
     * @author wrc
     * @date 2020/6/28
     */
    @Override
    public Wrapper<PageData<FreightSpaceListResponse>> freightSpaceList(FreightSpaceListRequest request, UserLoginCacheDTO sysUser) {
        //四舍五入，保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("#.00");

        FreightSpace freightSpace = new FreightSpace();
        freightSpace.setProductId(request.getProductId());
        freightSpace.setCategory(request.getCategory());
        freightSpace.setName(request.getName());
        freightSpace.setProductName(request.getProductName());
        freightSpace.setMemberId(sysUser.getMemberId());
        freightSpace.setCreateRoleId(sysUser.getMemberRoleId());
        freightSpace.setBrand(request.getBrand());
        freightSpace.setState(request.getState());
        freightSpace.setId(request.getId());
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("productName", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("category", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("brand", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<FreightSpace> example = Example.of(freightSpace, matcher);
        Page<FreightSpace> all = freightSpaceRepository.findAll(example, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        List<FreightSpace> freightSpaceList = all.getContent();

        //渠道商品不查上游供应信息
        HashMap<Long, Double> commodityStockMap = new HashMap<>();
        Integer memberType = sysUser.getMemberType();
        Integer memberRoleType = sysUser.getMemberRoleType();
        if(MemberTypeEnum.MERCHANT.getCode().equals(memberType) || MemberTypeEnum.MERCHANT_PERSONAL.getCode().equals(memberType) && RoleTypeEnum.SERVICE_CONSUMER.getCode().equals(memberRoleType)){
            //获取上游会员商品的sku 会员角色信息得为服务消费者
//            List<Long> upperCommoditySkuIdList = freightSpaceList.stream().map(FreightSpace::getUpperProductId).collect(Collectors.toList());
            List<FreightSpaceMember> spaceMembers = freightSpaceMemberRepository.findByMemberIdAndRoleIdAndFreightSpaceIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), freightSpaceList.stream().map(FreightSpace::getId).collect(Collectors.toSet()));
            List<Long> upperCommoditySkuIdList = freightSpaceList.stream().filter(freight -> spaceMembers.stream().anyMatch(spaceMember -> freight.getId().equals(spaceMember.getFreightSpaceId()))).map(FreightSpace::getUpperProductId).collect(Collectors.toList());
            //获取库存 商城类型需要为企业商城
            commodityStockMap = commodityService.getUpperCommoditySkuStock(sysUser.getMemberId(), ShopTypeEnum.ENTERPRISE.getCode(), upperCommoditySkuIdList);
        }
        HashMap<Long, Double> finalCommodityStockMap = commodityStockMap;
        List<FreightSpaceListResponse> list = freightSpaceList.stream().map(freightSpacedto -> {
            FreightSpaceListResponse freightSpaceListResponse = BeanUtil.copyProperties(freightSpacedto, FreightSpaceListResponse.class);
            freightSpaceListResponse.setUnit(freightSpacedto.getUnit());
            freightSpaceListResponse.setInventory(Double.parseDouble(decimalFormat.format(freightSpacedto.getInventory() == null ? 0 : freightSpacedto.getInventory())));
            freightSpaceListResponse.setAlreadyiInventory(Double.parseDouble(decimalFormat.format(freightSpacedto.getAlreadyInventory() == null ? 0 : freightSpacedto.getAlreadyInventory())));
            if(finalCommodityStockMap != null && finalCommodityStockMap.size() > 0){
                Long upperProductId = freightSpacedto.getUpperProductId();
                if(upperProductId != null && upperProductId > 0){
                    freightSpaceListResponse.setUpperStockCount(Double.parseDouble(decimalFormat.format(finalCommodityStockMap.get(upperProductId) == null ? 0 : finalCommodityStockMap.get(upperProductId))));
                }
            }else{
                freightSpaceListResponse.setUpperMemberName(null);
            }
            return freightSpaceListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(all.getTotalElements(), list));
    }

    /**
     * 停用&启用仓位库存管理
     *
     * @param request
     * @author wrc
     * @date 2020/6/28
     */
    @Override
    public Wrapper freightSpaceStopRoStart(FreightSpaceStopRoStartRequest request, UserLoginCacheDTO sysUser) {
        FreightSpace freightSpace = freightSpaceRepository.findById(request.getId()).orElse(null);
        if (freightSpace == null) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        freightSpace.setState(request.getState());
        freightSpaceRepository.saveAndFlush(freightSpace);
        //把库存存在redis中
        List<Long> list = new ArrayList<>();
        list.add(freightSpace.getProductId());
        inventorySynchronizationAll(list);
        return Wrapper.success();
    }

    /**
     * 新增仓位库存
     *
     * @author wrc
     * @date 2020/6/29
     */
    @Override
    public Wrapper freightSpaceAdd(FreightSpaceAddRequest request, UserLoginCacheDTO sysUser) {
        //验证商品id
        if (null == request.getProductId()) {
            return Wrapper.fail(ResponseCode.PRODUCTID_NOT_NULL);
        }
        //判断仓位名称不能重复
        if (freightSpaceRepository.existsAllByNameEqualsAndMemberIdAndCreateRoleId(request.getName(), sysUser.getMemberId(), sysUser.getMemberRoleId())) {
            return Wrapper.fail(ResponseCode.DUPLICATE_POSITION_NAME);
        }

        //查询仓库货品库存
        Inventory inventory = inventoryRepository.findByGoodsIdAndWarehouseIdEquals(request.getGoodsId(), request.getWarehouseId());
        FreightSpace freightSpace = new FreightSpace();
        freightSpace.setWarehouseId(request.getWarehouseId());
        if (null != request.getWarehouseId()) {
            Warehouse warehouse = warehouseRepository.findById(request.getWarehouseId()).orElse(null);
            freightSpace.setWarehouseName(null != warehouse ? warehouse.getName() : request.getWarehouseName());
        }

        //查询商品信息
        Long productId = request.getProductId();
        if(productId == null || productId < 0){
            return Wrapper.fail(ResponseCode.PRODUCTID_NOT_NULL);
        }
        CommodityUnitPriceAndPic commodityUnitPriceAndPic = commodityUnitPriceAndPicRepository.findById(productId).orElse(null);
        if(commodityUnitPriceAndPic == null){
            return Wrapper.fail(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
        }

        freightSpace.setGoodsName(request.getGoodsName());
        freightSpace.setItemNo(request.getItemNo());
        freightSpace.setInventoryDeductWay(request.getInventoryDeductWay());
        freightSpace.setProductId(productId);
        freightSpace.setUpperProductId(commodityUnitPriceAndPic.getUpperCommoditySkuId());
        freightSpace.setUpperMemberId(commodityUnitPriceAndPic.getCommodity().getUpperMemberId());
        freightSpace.setUpperMemberName(commodityUnitPriceAndPic.getCommodity().getUpperMemberName());
        freightSpace.setState(CommonConstant.State.STATE_START);
        freightSpace.setCategory(request.getCategory());
        freightSpace.setName(request.getName());
        freightSpace.setProductName(request.getProductName());
        freightSpace.setBrand(request.getBrand());
        freightSpace.setUnit(request.getUnit());
        //freightSpace.setAlreadyInventory((null == inventory || null == inventory.getInventory()) ? 0.0 : inventory.getInventory());
        freightSpace.setInventory(request.getInventory());
        freightSpace.setCreateTime(System.currentTimeMillis());
        freightSpace.setGoodsId(request.getGoodsId());
        freightSpace.setShopType(request.getShopType());
        freightSpace.setIsAllMemberShare(request.getIsAllMemberShare());
        freightSpace.setCreateRoleId(sysUser.getMemberRoleId());
        freightSpace.setMemberId(sysUser.getMemberId());
        freightSpaceRepository.saveAndFlush(freightSpace);

        //保存商城与仓位的关联关系
        List<ShopFreightSpace> list = new ArrayList<>();
        List<ShopRequest> shopIds = request.getShopIds();
        shopIds.forEach(shop -> {
            ShopFreightSpace shopFreightSpace = new ShopFreightSpace();
            shopFreightSpace.setFreightSpaceId(freightSpace.getId());
            shopFreightSpace.setShopId(shop.getId());
            shopFreightSpace.setType(shop.getType());
            shopFreightSpace.setEnvironment(shop.getEnvironment());
            list.add(shopFreightSpace);
        });
        shopFreightSpaceRepository.saveAll(list);
        shopFreightSpaceRepository.flush();
        if (InvoicesTypeConstant.IsAllMemberShare.NOT == freightSpace.getIsAllMemberShare()) {
            List<FreightSpaceMember> freightSpaceMembers = new ArrayList<>();
            List<ApplyMemberRequest> applyMember = request.getApplyMember();
            if (null != applyMember && applyMember.size() > 0) {
                applyMember.forEach(applyMemberRequest -> {
                    FreightSpaceMember freightSpaceMember = new FreightSpaceMember();
                    freightSpaceMember.setMemberId(applyMemberRequest.getMemberId());
                    freightSpaceMember.setFreightSpaceId(freightSpace.getId());
                    freightSpaceMember.setMemberTypeName(applyMemberRequest.getMemberTypeName());
                    freightSpaceMember.setName(applyMemberRequest.getName());
                    freightSpaceMember.setRoleName(applyMemberRequest.getRoleName());
                    freightSpaceMember.setRoleId(applyMemberRequest.getRoleId());
                    freightSpaceMember.setLevelTag(applyMemberRequest.getLevelTag());
                    freightSpaceMember.setLevel(applyMemberRequest.getLevel());
                    freightSpaceMembers.add(freightSpaceMember);
                });
                freightSpaceMemberRepository.saveAll(freightSpaceMembers);
                freightSpaceMemberRepository.flush();
            }
        }
        //把库存存在redis中
        List<Long> productIds = new ArrayList<>();
        productIds.add(freightSpace.getProductId());
        inventorySynchronizationAll(productIds);
        return Wrapper.success();
    }

    /**
     * 批量新增仓位库存
     * @author jw.chen
     * @date 2021/5/11
     */
    @Override
    public Wrapper freightSpaceAddBatch(FreightSpaceAddBatchRequest request, UserLoginCacheDTO sysUser) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();

        List<FreightSpaceCommodityRequest> commodityList = request.getCommodityList();
        commodityList.forEach(commodityRequest -> {
            String productName = commodityRequest.getProductName();
            Integer shopType = request.getShopType();
            String name = productName + "-" + ShopTypeEnum.getNameByCode(shopType);

            //验证商品id
            Long productId = commodityRequest.getProductId();
            if(productId == null || productId < 0){
                throw new BusinessException(ResponseCode.PRODUCTID_NOT_NULL);
            }
            CommodityUnitPriceAndPic commodityUnitPriceAndPic = commodityUnitPriceAndPicRepository.findById(productId).orElse(null);
            if(commodityUnitPriceAndPic == null){
                throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_NOT_EXIST);
            }

            //查询仓库货品库存
            Inventory inventory = inventoryRepository.findByGoodsIdAndWarehouseIdEquals(commodityRequest.getGoodsId(), request.getWarehouseId());
            FreightSpace freightSpace = new FreightSpace();
            freightSpace.setWarehouseId(request.getWarehouseId());
            if (null != request.getWarehouseId()) {
                Warehouse warehouse = warehouseRepository.findById(request.getWarehouseId()).orElse(null);
                freightSpace.setWarehouseName(null != warehouse ? warehouse.getName() : request.getWarehouseName());
            }
            freightSpace.setGoodsName(commodityRequest.getGoodsName());
            freightSpace.setItemNo(commodityRequest.getItemNo());
            freightSpace.setInventoryDeductWay(request.getInventoryDeductWay());
            freightSpace.setProductId(commodityRequest.getProductId());
            freightSpace.setUpperProductId(commodityUnitPriceAndPic.getUpperCommoditySkuId());
            freightSpace.setUpperMemberId(commodityUnitPriceAndPic.getCommodity().getUpperMemberId());
            freightSpace.setUpperMemberName(commodityUnitPriceAndPic.getCommodity().getUpperMemberName());
            freightSpace.setState(CommonConstant.State.STATE_START);
            freightSpace.setCategory(commodityRequest.getCategory());
            freightSpace.setName(getNewName(memberId, memberRoleId, name));
            freightSpace.setProductName(productName);
            freightSpace.setBrand(commodityRequest.getBrand());
            freightSpace.setUnit(commodityRequest.getUnit());
           // freightSpace.setAlreadyInventory((null == inventory || null == inventory.getInventory()) ? 0.0 : inventory.getInventory());
            freightSpace.setInventory(request.getInventory());
            freightSpace.setCreateTime(System.currentTimeMillis());
            freightSpace.setGoodsId(commodityRequest.getGoodsId());
            freightSpace.setShopType(shopType);
            freightSpace.setIsAllMemberShare(request.getIsAllMemberShare());
            freightSpace.setCreateRoleId(sysUser.getMemberRoleId());
            freightSpace.setMemberId(sysUser.getMemberId());
            freightSpaceRepository.saveAndFlush(freightSpace);

            //保存商城与仓位的关联关系
            List<ShopFreightSpace> list = new ArrayList<>();
            List<ShopRequest> shopIds = request.getShopIds();
            shopIds.forEach(shop -> {
                ShopFreightSpace shopFreightSpace = new ShopFreightSpace();
                shopFreightSpace.setFreightSpaceId(freightSpace.getId());
                shopFreightSpace.setShopId(shop.getId());
                shopFreightSpace.setType(shop.getType());
                shopFreightSpace.setEnvironment(shop.getEnvironment());
                list.add(shopFreightSpace);
            });
            shopFreightSpaceRepository.saveAll(list);
            shopFreightSpaceRepository.flush();
            if (InvoicesTypeConstant.IsAllMemberShare.NOT == freightSpace.getIsAllMemberShare()) {
                List<FreightSpaceMember> freightSpaceMembers = new ArrayList<>();
                List<ApplyMemberRequest> applyMember = request.getApplyMember();
                if (null != applyMember && applyMember.size() > 0) {
                    applyMember.forEach(applyMemberRequest -> {
                        FreightSpaceMember freightSpaceMember = new FreightSpaceMember();
                        freightSpaceMember.setMemberId(applyMemberRequest.getMemberId());
                        freightSpaceMember.setFreightSpaceId(freightSpace.getId());
                        freightSpaceMember.setMemberTypeName(applyMemberRequest.getMemberTypeName());
                        freightSpaceMember.setName(applyMemberRequest.getName());
                        freightSpaceMember.setRoleName(applyMemberRequest.getRoleName());
                        freightSpaceMember.setRoleId(applyMemberRequest.getRoleId());
                        freightSpaceMember.setLevelTag(applyMemberRequest.getLevelTag());
                        freightSpaceMember.setLevel(applyMemberRequest.getLevel());
                        freightSpaceMembers.add(freightSpaceMember);
                    });
                    freightSpaceMemberRepository.saveAll(freightSpaceMembers);
                    freightSpaceMemberRepository.flush();
                }
            }
            //把库存存在redis中
            List<Long> productIds = new ArrayList<>();
            productIds.add(freightSpace.getProductId());
            inventorySynchronizationAll(productIds);
        });
        return Wrapper.success();
    }

    /**
     * 获取不重复的仓位名称
     * @param memberId
     * @param name
     * @return
     */
    private String getNewName(Long memberId, Long memberRoleId, String name){
        //判断仓位名称是否重复
        Boolean flag = freightSpaceRepository.existsAllByNameEqualsAndMemberIdAndCreateRoleId(name, memberId, memberRoleId);
        if(flag){
            name = name + "_1";
            return getNewName(memberId, memberRoleId, name);
        }
        return name;
    }

    /**
     * 仓位库存详情查询
     *
     * @param request
     * @author wrc
     * @date 2020/7/8
     */
    @Override
    public Wrapper<FreightSpaceDetailsResponse> freightSpaceDetails(FreightSpaceDetailsRequest request, UserLoginCacheDTO sysUser) {
        Optional<FreightSpace> byId = freightSpaceRepository.findById(request.getId());
        if (!byId.isPresent()) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        FreightSpace freightSpace = byId.get();
        FreightSpaceDetailsResponse freightSpaceDetailsResponse = new FreightSpaceDetailsResponse();
        BeanUtils.copyProperties(freightSpace, freightSpaceDetailsResponse);
        freightSpaceDetailsResponse.setWarehouseId(freightSpace.getWarehouseId());
        freightSpaceDetailsResponse.setShopType(freightSpace.getShopType());
        freightSpaceDetailsResponse.setGoodsId(freightSpace.getGoodsId());
        freightSpaceDetailsResponse.setInventoryDeductWay(freightSpace.getInventoryDeductWay());
        freightSpaceDetailsResponse.setProductId(freightSpace.getProductId());
        freightSpaceDetailsResponse.setInventoryDeductWay(freightSpace.getInventoryDeductWay());
        freightSpaceDetailsResponse.setIsAllMemberShare(freightSpace.getIsAllMemberShare());
        freightSpaceDetailsResponse.setGoodsName(freightSpace.getGoodsName());
        //查询适用商城
        List<ShopFreightSpace> freightSpaces = shopFreightSpaceRepository.findByFreightSpaceIdEquals(request.getId());
        List<Long> shopIdList = freightSpaces.stream().map(ShopFreightSpace::getShopId).distinct().collect(Collectors.toList());
        freightSpaceDetailsResponse.setShopIds(shopIdList);
        if (null != freightSpace.getGoodsId() && null != freightSpace.getWarehouseId()) {
            Inventory inventory = inventoryRepository.findByGoodsIdAndWarehouseIdEquals(freightSpace.getGoodsId(), freightSpace.getWarehouseId());
            //freightSpaceDetailsResponse.setGoodsInventory((null == inventory || null == inventory.getInventory()) ? 0.0 : inventory.getInventory());
        }

        //获取上游会员商品的sku
        Long upperProductId = freightSpace.getUpperProductId();
        //适用会员角色信息得为服务消费者 且商城类型为企业商城
        Boolean result = freightSpaceMemberRepository.existsByMemberIdAndRoleIdAndFreightSpaceId(sysUser.getMemberId(), sysUser.getMemberRoleId(), freightSpace.getId());
        if(upperProductId != null && upperProductId > 0 && RoleTypeEnum.SERVICE_CONSUMER.getCode().equals(sysUser.getMemberRoleType()) && result){
            List<Long> upperCommoditySkuIdList = new ArrayList<>();
            upperCommoditySkuIdList.add(upperProductId);
            //获取库存
            HashMap<Long, Double> commodityStockMap = commodityService.getUpperCommoditySkuStock(sysUser.getMemberId(), ShopTypeEnum.ENTERPRISE.getCode(), upperCommoditySkuIdList);
            freightSpaceDetailsResponse.setUpperStockCount(commodityStockMap.get(upperProductId));
        }
        return Wrapper.success(freightSpaceDetailsResponse);
    }

    /**
     * 修改仓位信息
     *
     * @author wrc
     * @date 2020/7/9
     */
    @Transactional
    @Override
    public Wrapper freightSpaceUpdatat(FreightSpaceUpdataRequest request, UserLoginCacheDTO sysUser) {
        FreightSpace freightSpace = freightSpaceRepository.findById(request.getId()).orElse(null);
        if (freightSpace == null) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        //修改基础信息
        freightSpace.setInventory(request.getInventory());
        freightSpace.setInventoryDeductWay(request.getInventoryDeductWay());
        freightSpace.setUpdateTime(System.currentTimeMillis());
        freightSpace.setIsAllMemberShare(request.getIsAllMemberShare());
        freightSpace.setShopType(request.getShopType());
        //修改绑定商城
        shopFreightSpaceRepository.deleteAllByFreightSpaceIdEquals(request.getId());
        shopFreightSpaceRepository.flush();
        List<ShopRequest> shopIds = request.getShopIds();
        List<ShopFreightSpace> list = new ArrayList<>();
        shopIds.forEach(shop -> {
            ShopFreightSpace shopFreightSpace = new ShopFreightSpace();
            shopFreightSpace.setShopId(shop.getId());
            shopFreightSpace.setType(shop.getType());
            shopFreightSpace.setEnvironment(shop.getEnvironment());
            shopFreightSpace.setFreightSpaceId(request.getId());
            list.add(shopFreightSpace);
        });
        shopFreightSpaceRepository.saveAll(list);
        shopFreightSpaceRepository.flush();
        //修改绑定会员
        freightSpaceMemberRepository.deleteAllByFreightSpaceIdEquals(request.getId());
        freightSpaceMemberRepository.flush();
        if (InvoicesTypeConstant.IsAllMemberShare.NOT == freightSpace.getIsAllMemberShare()) {
            List<ApplyMemberRequest> applyMember = request.getApplyMember();
            List<FreightSpaceMember> applyMembers = new ArrayList<>();
            applyMember.forEach(applyMemberRequest -> {
                FreightSpaceMember freightSpaceMember = new FreightSpaceMember();
                freightSpaceMember.setFreightSpaceId(request.getId());
                freightSpaceMember.setMemberId(applyMemberRequest.getMemberId());
                freightSpaceMember.setMemberId(applyMemberRequest.getMemberId());
                freightSpaceMember.setMemberTypeName(applyMemberRequest.getMemberTypeName());
                freightSpaceMember.setName(applyMemberRequest.getName());
                freightSpaceMember.setRoleName(applyMemberRequest.getRoleName());
                freightSpaceMember.setRoleId(applyMemberRequest.getRoleId());
                freightSpaceMember.setLevelTag(applyMemberRequest.getLevelTag());
                freightSpaceMember.setLevel(applyMemberRequest.getLevel());
                applyMembers.add(freightSpaceMember);
            });
            freightSpaceMemberRepository.saveAll(applyMembers);
            freightSpaceMemberRepository.flush();
        }
        //把库存存在redis中
        inventorySynchronizationAll(Collections.singletonList(freightSpace.getProductId()));
        return Wrapper.success();
    }

    /**
     * 仓位库存信息批量修改
     * @param request
     * @param sysUser
     * @return
     */
    @Override
    public Wrapper freightSpaceUpdateBatch(FreightSpaceUpdateBatchRequest request, UserLoginCacheDTO sysUser) {
        DecimalFormat decimalFormat = new DecimalFormat("#.00");

        Integer type = request.getType();
        List<Long> idList = request.getIdList();
        List<FreightSpace> freightSpaceList = new ArrayList<>();
        List<Long> productIdList = new ArrayList<>();
        idList.forEach(id -> {
            FreightSpace freightSpace = freightSpaceRepository.findById(id).orElse(null);
            if (freightSpace == null) {
                throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
            }
            Double existInventory = freightSpace.getInventory();
            Double inventory = request.getInventory();
            if(type == 2){
                if(inventory < -100){
                    throw new BusinessException(ResponseCode.INVOICES_RATIO_EXCEPTIONN);
                }
                freightSpace.setInventory(Double.parseDouble(decimalFormat.format(existInventory * (100 + inventory) / 100)));
            }else{
                freightSpace.setInventory(inventory);
            }
            //修改基础信息
            freightSpace.setUpdateTime(System.currentTimeMillis());
            freightSpaceList.add(freightSpace);
            productIdList.add(freightSpace.getProductId());
        });
        freightSpaceRepository.saveAll(freightSpaceList);
        //把库存存在redis中
        inventorySynchronizationAll(productIdList);
        return Wrapper.success();
    }

    /**
     * 仓位库存调拨 调出
     *
     * @author wrc
     * @date 2020/7/9
     */
    @Override
    public Wrapper<FreightSpaceAllotFoldResponse> freightSpaceAllotExport(FreightSpaceAllotRequest request, UserLoginCacheDTO sysUser) {
        if (request.getFreightSpaceId().equals(request.getFoldFreightSpaceId())) {
            return Wrapper.fail(ResponseCode.WAREHOUSE_ID_REPETITION);
        }
        FreightSpaceAllotFoldResponse freightSpaceAllotFoldResponse = new FreightSpaceAllotFoldResponse();
        //调入的仓库
        Optional<FreightSpace> foldFreightSpaceOptional = freightSpaceRepository.findById(request.getFoldFreightSpaceId());
        if (!foldFreightSpaceOptional.isPresent()) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_EXIST);
        }
        FreightSpace foldFreightSpace = foldFreightSpaceOptional.get();
        //调入前库存
        Double foldFreightSpaceInventory = foldFreightSpace.getInventory();
        //调出的仓库
        Optional<FreightSpace> freightSpaceOptional = freightSpaceRepository.findById(request.getFreightSpaceId());
        if (!freightSpaceOptional.isPresent()) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_EXIST);
        }
        FreightSpace freightSpace = freightSpaceOptional.get();
        //判断仓位库存数是否满足调拨条件
        if (!freightSpaceInventoryIsAdequate(freightSpace, request.getFoldInventory())) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_ENOUGH);
        }
        //调出以前库存
        Double inventory = freightSpace.getInventory();
        //扣除被调拨出的仓位库存数量
        freightSpace.setInventory(inventory - request.getFoldInventory());
        freightSpace.setUpdateTime(System.currentTimeMillis());
        freightSpaceRepository.saveAndFlush(freightSpace);
        //增加被调拨入的仓位库存数量
        foldFreightSpace.setInventory(foldFreightSpace.getInventory() + request.getFoldInventory());
        foldFreightSpace.setUpdateTime(System.currentTimeMillis());
        freightSpaceRepository.saveAndFlush(foldFreightSpace);
        //生成调拨调出记录并记录下来
        FreightSpaceAllotLog freightSpaceAllotLog = new FreightSpaceAllotLog();
        freightSpaceAllotLog.setFreightSpaceId(request.getFreightSpaceId());
        freightSpaceAllotLog.setFoldInventory(request.getFoldInventory());
        freightSpaceAllotLog.setFoldFreightSpace(foldFreightSpace.getName());
        freightSpaceAllotLog.setFoldFreightSpaceId(foldFreightSpace.getId());
        freightSpaceAllotLog.setFoldRearInventory(freightSpace.getInventory());
        freightSpaceAllotLog.setUnit(freightSpace.getUnit());
        freightSpaceAllotLog.setFrontExportInventory(inventory);
        freightSpaceAllotLog.setExportFreightSpace(freightSpace.getName());
        freightSpaceAllotLog.setExportFreightSpaceId(freightSpace.getId());
        freightSpaceAllotLog.setExportProdouctId(freightSpace.getProductId());
        freightSpaceAllotLog.setExportProdouct(null == freightSpace.getProductName() ? "" : freightSpace.getProductName().concat("/").concat(null == freightSpace.getCategory() ? "" : freightSpace.getCategory()).concat(null == freightSpace.getUnit() ? "" : freightSpace.getUnit()));
        freightSpaceAllotLog.setExportInventory(request.getFoldInventory());
        freightSpaceAllotLog.setCreateTime(System.currentTimeMillis());
        freightSpaceAllotLog.setAllotTime(System.currentTimeMillis());
        freightSpaceAllotLog.setType(InvoicesTypeConstant.AllotType.EXPORT);
        freightSpaceAllotLogRepository.saveAndFlush(freightSpaceAllotLog);
        //生成调拨调入记录并记录下来
        FreightSpaceAllotLog foldFreightSpaceAllotLog = new FreightSpaceAllotLog();
        foldFreightSpaceAllotLog.setFreightSpaceId(request.getFoldFreightSpaceId());
        foldFreightSpaceAllotLog.setFoldInventory(request.getFoldInventory());
        foldFreightSpaceAllotLog.setFoldFreightSpace(foldFreightSpace.getName());
        foldFreightSpaceAllotLog.setFoldFreightSpaceId(foldFreightSpace.getId());
        foldFreightSpaceAllotLog.setFoldRearInventory(foldFreightSpace.getInventory());
        foldFreightSpaceAllotLog.setUnit(freightSpace.getUnit());
        foldFreightSpaceAllotLog.setFrontExportInventory(foldFreightSpaceInventory);
        foldFreightSpaceAllotLog.setExportFreightSpace(freightSpace.getName());
        foldFreightSpaceAllotLog.setExportFreightSpaceId(freightSpace.getId());
        foldFreightSpaceAllotLog.setExportProdouctId(freightSpace.getProductId());
        foldFreightSpaceAllotLog.setExportProdouct(null == freightSpace.getProductName() ? "" : freightSpace.getProductName().concat("/").concat(null == freightSpace.getCategory() ? "" : freightSpace.getCategory()).concat(null == freightSpace.getUnit() ? "" : freightSpace.getUnit()));
        foldFreightSpaceAllotLog.setExportInventory(request.getFoldInventory());
        foldFreightSpaceAllotLog.setCreateTime(System.currentTimeMillis());
        foldFreightSpaceAllotLog.setAllotTime(System.currentTimeMillis());
        foldFreightSpaceAllotLog.setType(InvoicesTypeConstant.AllotType.FOLD);
        freightSpaceAllotLogRepository.saveAndFlush(foldFreightSpaceAllotLog);
        freightSpaceAllotFoldResponse.setCallInInventory(foldFreightSpace.getInventory());
        freightSpaceAllotFoldResponse.setBringUpTheInventory(freightSpace.getInventory());
        //把库存存在redis中
        List<Long> productIds = new ArrayList<>();
        productIds.add(freightSpace.getProductId());
        inventorySynchronizationAll(productIds);
        return Wrapper.success(freightSpaceAllotFoldResponse);
    }

    /**
     * 仓位库存调拨-调入
     *
     * @author wrc
     * @date 2020/7/9
     */
    @Override
    public Wrapper<FreightSpaceAllotFoldResponse> freightSpaceAllotFold(FreightSpaceAllotRequest request, UserLoginCacheDTO sysUser) {
        if (request.getFreightSpaceId().equals(request.getFoldFreightSpaceId())) {
            return Wrapper.fail(ResponseCode.WAREHOUSE_ID_REPETITION);
        }
        //调入库存实体
        Optional<FreightSpace> foldFreightSpaceOptional = freightSpaceRepository.findById(request.getFoldFreightSpaceId());
        if (!foldFreightSpaceOptional.isPresent()) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_EXIST);
        }
        FreightSpace foldFreightSpace = foldFreightSpaceOptional.get();
        //调入前库存
        Double foldFreightSpaceInventory = foldFreightSpace.getInventory();
        //调出库存实体
        Optional<FreightSpace> freightSpaceOptional = freightSpaceRepository.findById(request.getFreightSpaceId());
        if (!freightSpaceOptional.isPresent()) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_EXIST);
        }
        FreightSpace freightSpace = freightSpaceOptional.get();
        //判断仓位库存数是否满足调拨条件
        if (!freightSpaceInventoryIsAdequate(freightSpace, request.getFoldInventory())) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_ENOUGH);
        }
        //调出以前库存
        Double inventory = freightSpace.getInventory();
        //扣除被调拨出的仓位库存数量
        foldFreightSpace.setInventory(foldFreightSpace.getInventory() + request.getFoldInventory());
        foldFreightSpace.setUpdateTime(System.currentTimeMillis());
        freightSpaceRepository.save(foldFreightSpace);
        //增加被调拨入的仓位库存数量
        freightSpace.setInventory(freightSpace.getInventory() - request.getFoldInventory());
        freightSpace.setUpdateTime(System.currentTimeMillis());
        freightSpaceRepository.save(freightSpace);
        //生成调拨记录并记录下来
        FreightSpaceAllotLog freightSpaceAllotLog = new FreightSpaceAllotLog();
        //绑定的仓位ID
        freightSpaceAllotLog.setFreightSpaceId(request.getFoldFreightSpaceId());
        freightSpaceAllotLog.setCreateTime(System.currentTimeMillis());
        freightSpaceAllotLog.setExportFreightSpace(freightSpace.getName());
        freightSpaceAllotLog.setExportFreightSpaceId(freightSpace.getId());
        freightSpaceAllotLog.setExportProdouctId(freightSpace.getProductId());
        freightSpaceAllotLog.setExportProdouct(null == foldFreightSpace.getProductName() ? "" : foldFreightSpace.getProductName().concat("/").concat(null == foldFreightSpace.getCategory() ? "" : foldFreightSpace.getCategory()).concat(null == freightSpace.getUnit() ? "" : freightSpace.getUnit()));
        freightSpaceAllotLog.setExportInventory(request.getFoldInventory());
        freightSpaceAllotLog.setFoldInventory(request.getFoldInventory());
        freightSpaceAllotLog.setFoldRearInventory(foldFreightSpace.getInventory());
        freightSpaceAllotLog.setFrontExportInventory(inventory);
        freightSpaceAllotLog.setUnit(foldFreightSpace.getUnit());
        freightSpaceAllotLog.setFoldFreightSpace(foldFreightSpace.getName());
        freightSpaceAllotLog.setFoldFreightSpaceId(foldFreightSpace.getId());
        freightSpaceAllotLog.setAllotTime(System.currentTimeMillis());
        freightSpaceAllotLog.setType(InvoicesTypeConstant.AllotType.FOLD);
        freightSpaceAllotLogRepository.save(freightSpaceAllotLog);
        //生成调拨记录并记录下来
        FreightSpaceAllotLog exportFreightSpaceAllotLog = new FreightSpaceAllotLog();
        //绑定的仓位ID
        exportFreightSpaceAllotLog.setFreightSpaceId(request.getFreightSpaceId());
        exportFreightSpaceAllotLog.setCreateTime(System.currentTimeMillis());
        exportFreightSpaceAllotLog.setExportFreightSpace(freightSpace.getName());
        exportFreightSpaceAllotLog.setExportFreightSpaceId(freightSpace.getId());
        exportFreightSpaceAllotLog.setExportProdouctId(freightSpace.getProductId());
        exportFreightSpaceAllotLog.setExportProdouct(null == foldFreightSpace.getProductName() ? "" : foldFreightSpace.getProductName().concat("/").concat(null == foldFreightSpace.getCategory() ? "" : foldFreightSpace.getCategory()).concat(null == freightSpace.getUnit() ? "" : freightSpace.getUnit()));
        exportFreightSpaceAllotLog.setExportInventory(request.getFoldInventory());
        exportFreightSpaceAllotLog.setFoldInventory(request.getFoldInventory());
        exportFreightSpaceAllotLog.setFoldRearInventory(foldFreightSpace.getInventory());
        exportFreightSpaceAllotLog.setFrontExportInventory(foldFreightSpaceInventory);
        exportFreightSpaceAllotLog.setUnit(foldFreightSpace.getUnit());
        exportFreightSpaceAllotLog.setFoldFreightSpace(foldFreightSpace.getName());
        exportFreightSpaceAllotLog.setFoldFreightSpaceId(foldFreightSpace.getId());
        exportFreightSpaceAllotLog.setAllotTime(System.currentTimeMillis());
        exportFreightSpaceAllotLog.setType(InvoicesTypeConstant.AllotType.EXPORT);
        freightSpaceAllotLogRepository.save(exportFreightSpaceAllotLog);
        FreightSpaceAllotFoldResponse freightSpaceAllotFoldResponse = new FreightSpaceAllotFoldResponse();
        freightSpaceAllotFoldResponse.setBringUpTheInventory(foldFreightSpace.getInventory());
        freightSpaceAllotFoldResponse.setCallInInventory(freightSpace.getInventory());
        //把库存存在redis中
        List<Long> productIds = new ArrayList<>();
        productIds.add(freightSpace.getProductId());
        inventorySynchronizationAll(productIds);
        return Wrapper.success(freightSpaceAllotFoldResponse);
    }

    /**
     * 判断仓位库存数是否满足调拨条件
     * @param freightSpace 库存
     * @param inventory 库存数量
     * @return true: 库存足够 false：库存不足
     */
    private Boolean freightSpaceInventoryIsAdequate(FreightSpace freightSpace, Double inventory) {
        double getInventory = freightSpace.getInventory() == null ? 0.0 : freightSpace.getInventory();
        return getInventory >= inventory;
    }


    /**
     * 根据商品ID查询仓位库存
     *
     * @author wrc
     * @date 2020/7/9
     */
    @Override
    public Wrapper<List<FreightSpaceProductIdListResponse>> freightSpaceByProductId(FreightSpaceProductIdListRequest request, UserLoginCacheDTO sysUser) {
        //四舍五入，保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("#.00");

        List<FreightSpace> allByProductIdEquals = freightSpaceRepository.findAllByProductIdEquals(request.getProductId());
        if (null == allByProductIdEquals || allByProductIdEquals.size() == 0) {
            return Wrapper.fail(ResponseCode.PRODUCT_NOT_FREIGHT_SPACE);
        }
        List<FreightSpaceProductIdListResponse> list = new ArrayList<>();
        allByProductIdEquals.forEach(freightSpace -> {
            FreightSpaceProductIdListResponse freightSpaceProductIdListResponse = new FreightSpaceProductIdListResponse();
            freightSpaceProductIdListResponse.setId(freightSpace.getId());
            freightSpaceProductIdListResponse.setName(freightSpace.getName());
            freightSpaceProductIdListResponse.setInventory(Double.parseDouble(decimalFormat.format(freightSpace.getInventory())));
            freightSpaceProductIdListResponse.setUnit(freightSpace.getUnit());
            list.add(freightSpaceProductIdListResponse);
        });
        return Wrapper.success(list);
    }

    /**
     * 查询全部仓位
     *
     * @author wrc
     * @date 2020/8/7
     */
    @Override
    public Wrapper<List<FreightSpaceListResponse>> freightSpaceAll() {
        List<FreightSpace> allByStateEquals = freightSpaceRepository.findAllByStateEquals(CommonConstant.State.STATE_START);
        List<FreightSpaceListResponse> collect = allByStateEquals.stream().map(temp -> {
            FreightSpaceListResponse obj = new FreightSpaceListResponse();
            obj.setCategory(temp.getCategory());
            obj.setAlreadyiInventory(temp.getAlreadyInventory());
            obj.setBrand(temp.getBrand());
            obj.setUnit(temp.getUnit());
            obj.setState(temp.getState());
            obj.setProductName(temp.getProductName());
            obj.setName(temp.getName());
            obj.setInventory(temp.getInventory());
            obj.setId(temp.getId());
            return obj;
        }).collect(Collectors.toList());
        return Wrapper.success(collect);
    }

    /**
     * 查询仓位调拨记录ID
     *
     * @param request
     * @author wrc
     * @date 2020/8/14
     */
    @Override
    public Wrapper<PageData<FreightSpaceAllotLogListResponse>> freightSpaceAllotFoldLog(FreightSpaceAllotLogListRequest request) {
        //四舍五入，保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("#.00");

        FreightSpaceAllotLog freightSpaceAllotLog = new FreightSpaceAllotLog();
        freightSpaceAllotLog.setFreightSpaceId(request.getId());
        Page<FreightSpaceAllotLog> freightSpaceAllotLogs = freightSpaceAllotLogRepository.findAll(Example.of(freightSpaceAllotLog), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").descending()));
        List<FreightSpaceAllotLog> freightSpaceAllotLogList = new ArrayList<>();
        long count = 0;
        if (freightSpaceAllotLogs.getTotalElements() > 0) {
            count = freightSpaceAllotLogs.getTotalElements();
            freightSpaceAllotLogList = freightSpaceAllotLogs.getContent();
        }
        List<FreightSpaceAllotLogListResponse> collect = freightSpaceAllotLogList.stream().map(temp -> {
            FreightSpaceAllotLogListResponse freightSpaceAllotLogListResponse = new FreightSpaceAllotLogListResponse();
            BeanUtils.copyProperties(temp, freightSpaceAllotLogListResponse);
            freightSpaceAllotLogListResponse.setExportProdouct(temp.getExportProdouct());
            freightSpaceAllotLogListResponse.setUnit(temp.getUnit());
            freightSpaceAllotLogListResponse.setFreightSpaceId(temp.getFreightSpaceId());
            freightSpaceAllotLogListResponse.setType(temp.getType());
            //格式化
            freightSpaceAllotLogListResponse.setExportInventory(Double.parseDouble(decimalFormat.format(freightSpaceAllotLogListResponse.getExportInventory() == null ? 0 : freightSpaceAllotLogListResponse.getExportInventory())));
            freightSpaceAllotLogListResponse.setFoldInventory(Double.parseDouble(decimalFormat.format(freightSpaceAllotLogListResponse.getFoldInventory() == null ? 0 : freightSpaceAllotLogListResponse.getFoldInventory())));
            freightSpaceAllotLogListResponse.setFoldRearInventory(Double.parseDouble(decimalFormat.format(freightSpaceAllotLogListResponse.getFoldRearInventory() == null ? 0 : freightSpaceAllotLogListResponse.getFoldRearInventory())));
            freightSpaceAllotLogListResponse.setFrontExportInventory(Double.parseDouble(decimalFormat.format(freightSpaceAllotLogListResponse.getFrontExportInventory() == null ? 0 : freightSpaceAllotLogListResponse.getFrontExportInventory())));
            return freightSpaceAllotLogListResponse;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(count, collect));
    }

    /**
     * 根据仓位ID查询仓位绑定的会员
     *
     * @author wrc
     * @date 2020/9/18
     */
    @Override
    public Wrapper<PageData<ApplyMemberRequest>> freightSpaceMamberList(FreightSpaceAllotLogListRequest request) {
        List<ApplyMemberRequest> list = new ArrayList<>();
        long count = 0L;
        FreightSpaceMember freightSpaceMember = new FreightSpaceMember();
        freightSpaceMember.setFreightSpaceId(request.getId());
        Page<FreightSpaceMember> freightSpaceMemberPage = freightSpaceMemberRepository.findAll(Example.of(freightSpaceMember), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").descending()));
        if (freightSpaceMemberPage.getTotalElements() > 0) {
            count = freightSpaceMemberPage.getTotalElements();
            list = freightSpaceMemberPage.getContent().stream().map(temp -> {
                ApplyMemberRequest freightSpaceMemberRequest = new ApplyMemberRequest();
                freightSpaceMemberRequest.setMemberId(temp.getMemberId());
                freightSpaceMemberRequest.setMemberId(temp.getMemberId());
                freightSpaceMemberRequest.setMemberTypeName(temp.getMemberTypeName());
                freightSpaceMemberRequest.setName(temp.getName());
                freightSpaceMemberRequest.setRoleName(temp.getRoleName());
                freightSpaceMemberRequest.setRoleId(temp.getRoleId());
                freightSpaceMemberRequest.setLevelTag(temp.getLevelTag());
                freightSpaceMemberRequest.setLevel(temp.getLevel());
                return freightSpaceMemberRequest;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(count, list));
    }

    /**
     * 扣除商品库存
     *
     * @author wrc
     * @date 2020/9/8
     */
    @Transactional
    @Override
    public Wrapper<Void> deductInventory(InventoryByProductIdRequest request) {
        List<DeductInventoryRequest> deductInventoryRequests = request.getDeductInventoryRequests();
        List<FreightSpace> freightSpaceList = getFreightSpace(request);
        if (CollectionUtils.isEmpty(freightSpaceList)) {
            return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_ENOUGH);
        }
        List<FreightSpace> list = new ArrayList<>();
        //按照商品ID分组
        Map<Long, List<FreightSpace>> freightSpaceMap = freightSpaceList.stream().collect(Collectors.groupingBy(FreightSpace::getProductId));
        //统计商品的总库存
        Map<Long, Double> collect = freightSpaceList.stream().collect(Collectors.groupingBy(FreightSpace::getProductId, Collectors.summingDouble(FreightSpace::getInventory)));
        List<PositionInventoryDeductionRecord> positionInventoryDeductionRecords = new ArrayList<>();
        for (DeductInventoryRequest deductInventoryRequest : deductInventoryRequests) {
            Long productSkuId = deductInventoryRequest.getProductSkuId();

            RedisLockUtil.lock(InvoicesTypeConstant.redisKey + productSkuId, 50, TimeUnit.SECONDS);
            //需要扣除的库存
            Double purchaseCount = deductInventoryRequest.getPurchaseCount();
            //商品的总库存
            Double inventory = null == collect.get(productSkuId) ? 0.0 : collect.get(productSkuId);
            if (purchaseCount > inventory) {
                RedisLockUtil.unlock(InvoicesTypeConstant.redisKey + productSkuId.toString());
                return Wrapper.fail(ResponseCode.FREIGHT_SPACE_INVENTORY_NOT_ENOUGH);
            }
            List<FreightSpace> freightSpaces = freightSpaceMap.get(productSkuId);
            //随机扣除库存
            for (FreightSpace freightSpace : freightSpaces) {
                if (freightSpace.getInventory() <= 0 || purchaseCount == 0) {
                    continue;
                }
                PositionInventoryDeductionRecord pidr = new PositionInventoryDeductionRecord();
                pidr.setBeforeDeductionInventory(freightSpace.getInventory());
                pidr.setType(InvoicesTypeConstant.PositionInventoryDeductionRecordType.PLACE_ORDER);
                pidr.setCreateMemberId(freightSpace.getMemberId());
                pidr.setCreateRoleId(freightSpace.getCreateRoleId());
                pidr.setWarehouseName(freightSpace.getWarehouseName());
                pidr.setWarehouseId(freightSpace.getWarehouseId());
                pidr.setProductId(deductInventoryRequest.getProductId());
                pidr.setProductSkuId(deductInventoryRequest.getProductSkuId());
                pidr.setChannelProductId(deductInventoryRequest.getChannelProductId());
                pidr.setChannelProductSkuId(deductInventoryRequest.getChannelProductSkuId());
                pidr.setProductName(StringUtils.isNotEmpty(deductInventoryRequest.getProductName()) ? deductInventoryRequest.getProductName() : deductInventoryRequest.getChannelProductName());
                pidr.setGoodsName(freightSpace.getGoodsName());
                pidr.setGoodsId(freightSpace.getGoodsId());
                pidr.setFreightSpaceName(freightSpace.getName());
                pidr.setState(EnableDisableStatus.DISABLE.getCode());
                pidr.setFreightSpaceId(freightSpace.getId());
                pidr.setCreateTime(System.currentTimeMillis());
                pidr.setOrderId(request.getOrderId());
                //已用库存
                Double alreadyInventory = freightSpace.getAlreadyInventory() == null ? 0 : freightSpace.getAlreadyInventory();
                if (freightSpace.getInventory() >= purchaseCount) {
                    Double endDeductionInventory = freightSpace.getInventory() - purchaseCount;
                    pidr.setReductionInventory(purchaseCount);
                    pidr.setEndDeductionInventory(endDeductionInventory);
                    freightSpace.setInventory(endDeductionInventory);
                    freightSpace.setAlreadyInventory(alreadyInventory + purchaseCount);
                    purchaseCount = 0.0;
                } else if (purchaseCount >= freightSpace.getInventory()) {
                    Double existInventory = freightSpace.getInventory();
                    pidr.setReductionInventory(freightSpace.getInventory());
                    pidr.setEndDeductionInventory(0.0);
                    freightSpace.setInventory(0.0);
                    freightSpace.setAlreadyInventory(alreadyInventory + existInventory);
                    purchaseCount = purchaseCount - existInventory;
                }
                positionInventoryDeductionRecords.add(pidr);
            }
            list.addAll(freightSpaces);
        }
        freightSpaceRepository.saveAll(list);
        //生成记录
        positionInventoryDeductionRecordRepository.saveAll(positionInventoryDeductionRecords);
        for (DeductInventoryRequest deductInventoryRequest : deductInventoryRequests) {
            RedisLockUtil.unlock(InvoicesTypeConstant.redisKey + deductInventoryRequest.getProductSkuId().toString());
        }
        //把库存存在redis中
        List<Long> productIds = request.getDeductInventoryRequests().stream().map(DeductInventoryRequest::getProductSkuId).collect(Collectors.toList());
        inventorySynchronizationAll(productIds);
        return Wrapper.success();
    }

    /**
     * 查询商品的仓位集合
     *
     * @author wrc
     * @date 2020/11/4
     */
    private List<FreightSpace> getFreightSpace(InventoryByProductIdRequest request) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT " +
                "f.id as id,f.name as name,f.warehouse_id as warehouseId,f.warehouse_name as warehouseName,f.product_name as productName,f.category as category,f.brand as brand,f.unit as unit,f.inventory as inventory,f.already_inventory as alreadyInventory,f.inventory_deduct_way as inventoryDeductWay," +
                "f.state as state,f.product_id as productId,f.create_time as createTime,f.update_time as updateTime,f.create_role_id as createRoleId,f.member_id as memberId,f.item_no as itemNo,f.goods_id as goodsId,f.goods_name as goodsName,f.is_all_member_share as isAllMemberShare,f.shop_type as shopType,f.upper_member_id as upperMemberId,f.upper_member_name as upperMemberName,f.upper_product_id as upperProductId " +
                " FROM wh_freight_space f LEFT JOIN wh_freight_space_member M ON f.ID = M.freight_space_id  left join wh_shop_freight_space s on f.id=s.freight_space_id  WHERE ( M.member_id = ");
        sql.append(request.getSupplyMembersId());
        sql.append(" and  M.role_id =").append(request.getMemberRoleId()).append(" OR f.is_all_member_share = 1) AND f.state = 1  and s.shop_id=").append(request.getShopId()).append(" AND f.product_id in( ");
        sql.append(CollectionUtil.join(request.getDeductInventoryRequests().stream().map(DeductInventoryRequest::getProductSkuId).collect(Collectors.toList()), ","));
        sql.append(")");
        return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(FreightSpace.class));
    }


    /**
     * 返回库存
     *
     * @author wrc
     * @date 2020/9/16
     */
    @Transactional
    @Override
    public Wrapper<Void> deductReturn(InventoryByProductIdRequest request) {
        //查询下单时的扣减记录
        List<PositionInventoryDeductionRecord> positionInventoryDeductionRecordList = positionInventoryDeductionRecordRepository.findByOrderIdEqualsAndTypeEqualsAndStateEquals(request.getOrderId(), InvoicesTypeConstant.PositionInventoryDeductionRecordType.PLACE_ORDER, EnableDisableStatus.DISABLE.getCode(), Sort.by("id").descending());
        if (CollectionUtils.isEmpty(positionInventoryDeductionRecordList)) {
            return Wrapper.success();
        }
        List<PositionInventoryDeductionRecord> positionInventoryDeductionRecords = new ArrayList<>();
        //按仓位ID分组
        Map<Long, List<PositionInventoryDeductionRecord>> map = positionInventoryDeductionRecordList.stream().collect(Collectors.groupingBy(PositionInventoryDeductionRecord::getFreightSpaceId));
        List<FreightSpace> freightSpaceList = freightSpaceRepository.findAllById(map.keySet());
        Map<Long, FreightSpace> freightSpaceMap = freightSpaceList.stream().collect(Collectors.toMap(FreightSpace::getId, FreightSpace -> FreightSpace));
        Set<Long> collect = freightSpaceList.stream().map(FreightSpace::getProductId).collect(Collectors.toSet());
        for (Long productId : collect) {
            RedisLockUtil.lock(productId.toString(), 10, TimeUnit.SECONDS);
        }
        //返回库存
        for (PositionInventoryDeductionRecord pos : positionInventoryDeductionRecordList) {
            Long productSkuId = pos.getProductSkuId();
            List<DeductInventoryRequest> deductInventoryRequests = request.getDeductInventoryRequests();
            deductInventoryRequests.forEach(deductInventoryRequest -> {
                Long requestProductId = deductInventoryRequest.getProductSkuId();
                Double purchaseCount = deductInventoryRequest.getPurchaseCount();
                //只返回对应商品sku的库存
                if(requestProductId.equals(productSkuId)){
                    FreightSpace freightSpace = freightSpaceMap.get(pos.getFreightSpaceId());
                    //已扣库存
                    Double returnInventory = pos.getReductionInventory();
                    if(returnInventory >= purchaseCount){
                        //返还后库存
                        Double endDeductionInventory = BigDecimal.valueOf(freightSpace.getInventory()).add(new BigDecimal(purchaseCount)).doubleValue();
                        //生成操作记录
                        PositionInventoryDeductionRecord positionInventoryDeductionRecord = new PositionInventoryDeductionRecord();
                        positionInventoryDeductionRecord.setBeforeDeductionInventory(freightSpace.getInventory());
                        positionInventoryDeductionRecord.setReductionInventory(purchaseCount);
                        positionInventoryDeductionRecord.setEndDeductionInventory(endDeductionInventory);
                        positionInventoryDeductionRecord.setType(InvoicesTypeConstant.PositionInventoryDeductionRecordType.CANCEL_ORDER_AND_RETURN_INVENTORY);
                        positionInventoryDeductionRecord.setCreateMemberId(request.getSupplyMembersId());
                        positionInventoryDeductionRecord.setCreateRoleId(request.getMemberRoleId());
                        positionInventoryDeductionRecord.setWarehouseName(freightSpace.getWarehouseName());
                        positionInventoryDeductionRecord.setWarehouseId(freightSpace.getWarehouseId());
                        positionInventoryDeductionRecord.setProductId(deductInventoryRequest.getProductId());
                        positionInventoryDeductionRecord.setProductSkuId(deductInventoryRequest.getProductSkuId());
                        positionInventoryDeductionRecord.setChannelProductId(deductInventoryRequest.getChannelProductId());
                        positionInventoryDeductionRecord.setChannelProductSkuId(deductInventoryRequest.getChannelProductSkuId());
                        positionInventoryDeductionRecord.setProductName(StringUtils.isNotEmpty(deductInventoryRequest.getProductName()) ? deductInventoryRequest.getProductName() : deductInventoryRequest.getChannelProductName());
                        positionInventoryDeductionRecord.setGoodsName(freightSpace.getGoodsName());
                        positionInventoryDeductionRecord.setGoodsId(freightSpace.getGoodsId());
                        positionInventoryDeductionRecord.setFreightSpaceName(freightSpace.getName());
                        positionInventoryDeductionRecord.setFreightSpaceId(freightSpace.getId());
                        positionInventoryDeductionRecord.setCreateTime(System.currentTimeMillis());
                        positionInventoryDeductionRecord.setOrderId(request.getOrderId());
                        positionInventoryDeductionRecord.setState(EnableDisableStatus.ENABLE.getCode());
                        positionInventoryDeductionRecords.add(positionInventoryDeductionRecord);
                        pos.setState(EnableDisableStatus.ENABLE.getCode());
                        freightSpace.setInventory(endDeductionInventory);
                        freightSpace.setUpdateTime(System.currentTimeMillis());
                        positionInventoryDeductionRecords.add(pos);
                    }
                }
            });
        }
        freightSpaceRepository.saveAll(freightSpaceList);
        //生成记录
        positionInventoryDeductionRecordRepository.saveAll(positionInventoryDeductionRecords);
        for (Long productId : collect) {
            RedisLockUtil.unlock(productId.toString());
        }
        //把库存存在redis中
        inventorySynchronizationAll(request.getDeductInventoryRequests().stream().map(DeductInventoryRequest::getProductSkuId).collect(Collectors.toList()));
        return Wrapper.success();
    }

    /**
     * 根据商品ID查询仓位扣减记录
     *
     * @author wrc
     * @date 2020/9/24
     */
    @Override
    public Wrapper<PageData<PositionInventoryDeductionRecordResponse>> positionDeductionRecordList(UserLoginCacheDTO sysUser, PositionInventoryDeductionRecordRequest request) {
        List<PositionInventoryDeductionRecordResponse> list = new ArrayList<>();
        long count = 0L;
        PositionInventoryDeductionRecord positionInventoryDeductionRecord = new PositionInventoryDeductionRecord();
        Long productId = request.getProductId();
        Long stockId = request.getStockId();
        if(stockId != null && stockId > 0){
            positionInventoryDeductionRecord.setChannelProductSkuId(productId);
        }else{
            positionInventoryDeductionRecord.setProductSkuId(productId);
        }
        positionInventoryDeductionRecord.setCreateRoleId(sysUser.getMemberRoleId());
        positionInventoryDeductionRecord.setCreateMemberId(sysUser.getMemberId());
        Example.of(positionInventoryDeductionRecord);
        Page<PositionInventoryDeductionRecord> positionInventoryDeductionRecords = positionInventoryDeductionRecordRepository.findAll(Example.of(positionInventoryDeductionRecord), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").descending()));
        if (positionInventoryDeductionRecords.getTotalElements() > 0) {
            count = positionInventoryDeductionRecords.getTotalElements();
            list = positionInventoryDeductionRecords.getContent().stream().map(temp -> {
                PositionInventoryDeductionRecordResponse positionInventoryDeductionRecordResponse = new PositionInventoryDeductionRecordResponse();
                BeanUtils.copyProperties(temp, positionInventoryDeductionRecordResponse);
                return positionInventoryDeductionRecordResponse;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(count, list));
    }

    /**
     * 根据商品ID查询仓位扣减记录- 平台后台
     */
    @Override
    public Wrapper<PageData<PositionInventoryDeductionRecordResponse>> platformPositionDeductionRecordList(UserLoginCacheDTO sysUser, PositionInventoryDeductionRecordRequest request) {
        List<PositionInventoryDeductionRecordResponse> list = new ArrayList<>();
        long count = 0L;
        PositionInventoryDeductionRecord positionInventoryDeductionRecord = new PositionInventoryDeductionRecord();
        Long productId = request.getProductId();
        Long stockId = request.getStockId();
        if(stockId != null && stockId > 0){
            positionInventoryDeductionRecord.setChannelProductSkuId(productId);
        }else{
            positionInventoryDeductionRecord.setProductSkuId(productId);
        }
        Example.of(positionInventoryDeductionRecord);
        Page<PositionInventoryDeductionRecord> positionInventoryDeductionRecords = positionInventoryDeductionRecordRepository.findAll(Example.of(positionInventoryDeductionRecord), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").descending()));
        if (positionInventoryDeductionRecords.getTotalElements() > 0) {
            count = positionInventoryDeductionRecords.getTotalElements();
            list = positionInventoryDeductionRecords.getContent().stream().map(temp -> {
                PositionInventoryDeductionRecordResponse positionInventoryDeductionRecordResponse = new PositionInventoryDeductionRecordResponse();
                BeanUtils.copyProperties(temp, positionInventoryDeductionRecordResponse);
                return positionInventoryDeductionRecordResponse;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(count, list));
    }

    /**
     * 查询商品的仓位库存
     */
    @Override
    public Wrapper<Double> stockByProductId(StockByProductIdRequest request, UserLoginCacheDTO sysUser) {
        String sql = "select sum(w.inventory) FROM wh_freight_space w left join wh_freight_space_member m on w.id=m.freight_space_id left join wh_shop_freight_space s on w.id=s.freight_space_id " +
                "where (w.is_all_member_share=1 or m.member_id=" + sysUser.getMemberId() + " and m.role_id=" + sysUser.getMemberRoleId() + ") and s.shop_id=" + request.getShopId() + " and w.product_id=" + request.getProductId();
        Double aDouble = jdbcTemplate.queryForObject(sql, Double.class);
        return Wrapper.success(null == aDouble ? 0D : aDouble);
    }

    /**
     * 查询商品的仓位库存
     */
    @Override
    public Wrapper<Double> stockByProductIdInside(Long productId, Long shopId, Long memberId, Long memberRoleId) {
        String sql;
        if (memberId != null && memberId > 0) {
            sql = "select sum(w.inventory) FROM wh_freight_space w left join wh_freight_space_member m on w.id=m.freight_space_id left join wh_shop_freight_space s on w.id=s.freight_space_id " +
                    "where (w.is_all_member_share=1 or m.member_id=" + memberId + " and m.role_id=" + memberRoleId + ") and s.shop_id=" + shopId + " and w.product_id=" + productId;
        } else {
            sql = "select sum(w.inventory) FROM wh_freight_space w left join wh_freight_space_member m on w.id=m.freight_space_id left join wh_shop_freight_space s on w.id=s.freight_space_id " +
                    "where w.is_all_member_share=1 and s.shop_id=" + shopId + " and w.product_id=" + productId;
        }
        Double aDouble = jdbcTemplate.queryForObject(sql, Double.class);
        return Wrapper.success(null == aDouble ? 0D : aDouble);
    }

    /**
     * 批量查询商品的仓位库存-内部
     */
    @Override
    public Wrapper<List<StockByProductIdsResponse>> stockByProductIdInsides(StockByProductIdsRequest request) {
        String sql = "select w.product_id as productId, sum(w.inventory) as stock  FROM wh_freight_space w left join wh_freight_space_member m on w.id=m.freight_space_id left join wh_shop_freight_space s on w.id=s.freight_space_id " +
                "where (w.is_all_member_share=1 or m.member_id=" + request.getMemberId() + " and m.role_id=" + request.getMemberRoleId() + ") and s.shop_id=" + request.getShopId() + " and w.product_id in(" + CollectionUtil.join(request.getProductIds(), ",") + ") GROUP BY productId";
        List<StockByProductIdsResponse> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(StockByProductIdsResponse.class));
        return Wrapper.success(query);
    }


    /**
     *筛选适用会员角色为服务消费者的商品SKU
     */
    @Override
    public Wrapper<List<Long>> stockByProductIdInsides(List<Long> skuIds, Long memberId, Long memberRoleId) {
        List<FreightSpace> freightSpaces = freightSpaceRepository.findByProductIdInAndState(skuIds, FreightStatusEnum.Enable.getCode());
        List<FreightSpaceMember> spaceMembers = freightSpaceMemberRepository.findByMemberIdAndRoleIdAndFreightSpaceIdIn(memberId, memberRoleId, freightSpaces.stream().map(FreightSpace::getId).collect(Collectors.toSet()));
        List<Long> skuids = freightSpaces.stream().filter(freight -> spaceMembers.stream().anyMatch(spaceMember -> freight.getId().equals(spaceMember.getFreightSpaceId()))).map(FreightSpace::getUpperProductId).collect(Collectors.toList());
        return CollectionUtils.isEmpty(skuids)? Wrapper.success(new ArrayList<>()) : Wrapper.success(skuIds);
    }

    /**
     * redis库存初始化
     */
    @Override
    public void syncFreightSpace() {
        redisStringUtils.delByPrex(CommonConstant.FREIGHT_SPACE_REDIS_KEY, Constants.REDIS_PRODUCT_INDEX);
        //查询所有仓位
        List<FreightSpace> freightSpaceList = freightSpaceRepository.findByState(FreightStatusEnum.Enable.getCode());
        List<Long> productIdList = freightSpaceList.stream().map(FreightSpace::getProductId).distinct().collect(Collectors.toList());
        if (productIdList.size() > 0) {
            this.inventorySynchronizationAll(productIdList);
        }
        log.info("redis中仓位库存初始化成功");
    }

    /**
     * 仓位库存列表修改库存
     * @param request 参数
     */
    @Transactional
    @Override
    public Boolean updateInventory(FreightSpaceUpdateInventoryRequest request, UserLoginCacheDTO sysUser) {
        Long id = request.getId();
        if(id != null && id > 0){
            FreightSpace freightSpace = freightSpaceRepository.findById(id).orElse(null);
            if(freightSpace != null && freightSpace.getMemberId().equals(sysUser.getMemberId()) && freightSpace.getCreateRoleId().equals(sysUser.getMemberRoleId())){
                freightSpace.setInventory(request.getInventory());
                freightSpaceRepository.saveAndFlush(freightSpace);

                //同步redis中的库存
                List<Long> productIdList = new ArrayList<>();
                productIdList.add(freightSpace.getProductId());
                this.inventorySynchronizationAll(productIdList);
                return true;
            }
        }
        throw new BusinessException(ResponseCode.RECORDS_DON_T_EXIST);
    }


    /**
     * 批量把会员库存缓存到redis中去
     */
    private void inventorySynchronizationAll(List<Long> productIds) {
        //四舍五入，保留两位小数
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        //先清除原来的数据
        List<String> removeProductIdList = new ArrayList<>();
        //查询商品对应仓位
        List<FreightSpace> freightSpaceList = freightSpaceRepository.findByProductIdInAndState(productIds, FreightStatusEnum.Enable.getCode());
        //查询仓位对应的商城
        List<Long> freightSpaceIdList = freightSpaceList.stream().map(FreightSpace::getId).collect(Collectors.toList());
        List<ShopFreightSpace> shopFreightSpaceList = shopFreightSpaceRepository.findByFreightSpaceIdIn(freightSpaceIdList);
        HashMap<Long, List<String>> shopFreightSpaceMap = new HashMap<>();
        shopFreightSpaceList.forEach(shopFreightSpace -> {
            Long freightSpaceId = shopFreightSpace.getFreightSpaceId();
            Long shopId = shopFreightSpace.getShopId();
//            Integer type = shopFreightSpace.getType();
//            Integer environment = shopFreightSpace.getEnvironment();
            if (shopId != null) {
                List<String> existShopFreightSpaceList = shopFreightSpaceMap.get(freightSpaceId);
                if (existShopFreightSpaceList == null || existShopFreightSpaceList.size() == 0) {
                    existShopFreightSpaceList = new ArrayList<>();
                }
                existShopFreightSpaceList.add(shopId + "_");
                shopFreightSpaceMap.put(freightSpaceId, existShopFreightSpaceList);
            }
        });
        //查询仓位对应的会员
        freightSpaceIdList = freightSpaceList.stream().filter(freightSpace -> freightSpace.getIsAllMemberShare() == InvoicesTypeConstant.IsAllMemberShare.NOT).map(FreightSpace::getId).collect(Collectors.toList());
        List<FreightSpaceMember> freightSpaceMemberList = freightSpaceMemberRepository.findByFreightSpaceIdIn(freightSpaceIdList);
        HashMap<Long, List<Long>> freightSpaceMemberMap = new HashMap<>();
        freightSpaceMemberList.forEach(freightSpaceMember -> {
            Long freightSpaceId = freightSpaceMember.getFreightSpaceId();
            Long memberId = freightSpaceMember.getMemberId();
            List<Long> existFreightSpaceMemberList = freightSpaceMemberMap.get(freightSpaceId);
            if (existFreightSpaceMemberList == null) {
                existFreightSpaceMemberList = new ArrayList<>();
            }
            existFreightSpaceMemberList.add(memberId);
            freightSpaceMemberMap.put(freightSpaceId, existFreightSpaceMemberList);
        });
        //组装数据
        HashMap<String, Map<String, String>> allStockMap = new HashMap<>();
        freightSpaceList.forEach(freightSpace -> {
            Long freightSpaceId = freightSpace.getId();
            Integer isAllMemberShare = freightSpace.getIsAllMemberShare();
            Long productId = freightSpace.getProductId();
            Double inventory = freightSpace.getInventory();
            List<String> shopIdList = shopFreightSpaceMap.get(freightSpaceId);
            if (shopIdList != null && shopIdList.size() > 0) {
                shopIdList.forEach(shopId -> {
                    String redisKey = CommonConstant.FREIGHT_SPACE_REDIS_KEY + shopId + productId;
                    Map<String, String> map = allStockMap.get(redisKey);
                    if (map == null || map.size() <= 0) {
                        map = new HashMap<>();
                    }
                    //所有会员共享
                    if (InvoicesTypeConstant.IsAllMemberShare.YES == isAllMemberShare) {
                        String existInventory = map.get("all");
                        if (StrUtil.isNotEmpty(existInventory)) {
                            Double newInventory = Double.parseDouble(decimalFormat.format(Double.parseDouble(existInventory) + inventory));
                            map.put("all", String.valueOf(newInventory));
                        } else {
                            map.put("all", String.valueOf(inventory));
                        }
                    } else {
                        List<Long> memberIdList = freightSpaceMemberMap.get(freightSpaceId);
                        Map<String, String> finalMap = map;
                        memberIdList.forEach(memberId -> {
                            String existInventory = finalMap.get(String.valueOf(memberId));
                            if (StrUtil.isNotEmpty(existInventory)) {
                                Double newInventory = Double.parseDouble(decimalFormat.format(Double.parseDouble(existInventory) + inventory));
                                finalMap.put(String.valueOf(memberId), String.valueOf(newInventory));
                            } else {
                                finalMap.put(String.valueOf(memberId), String.valueOf(inventory));
                            }
                        });
                    }
                    if (!removeProductIdList.contains(redisKey)) {
                        removeProductIdList.add(redisKey);
                    }
                    allStockMap.put(redisKey, map);
                });
            }
        });
        //删除旧数据
        if (removeProductIdList.size() > 0) {
            redisStringUtils.del(removeProductIdList, Constants.REDIS_PRODUCT_INDEX);
        }

        //把会员库存存在redis中
        if (allStockMap.size() > 0) {
            redisStringUtils.hMSetBatch(allStockMap, Constants.REDIS_PRODUCT_INDEX);
        }
    }

    /**
     * 根据商品ID查询默认所有会员共享的仓位
     * @author wrc
     * @date 2020/9/7
     */
    private List<FreightSpaceInventoryResponse> getFreightSpaceByProductIds(List<Long> productIds) {
        if (CollectionUtils.isEmpty(productIds)) {
            return null;
        }
        String sql = "select shop_type as shopType,product_id as productId,sum(inventory) as inventory from wh_freight_space where product_id in(" +
                productIds.stream().map(String::valueOf).collect(Collectors.joining(",")) +
                ") and is_all_member_share =1 and state =1 GROUP BY product_id,shop_type";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(FreightSpaceInventoryResponse.class));
    }
}
